import {
    _decorator,
    color,
    Component,
    Input,
    input,
    KeyCode,
    Node,
    Sprite,
    tween,
    Tween,
} from 'cc';
const { ccclass, property } = _decorator;

@ccclass('BlackNode')
export class BlackNode extends Component {
    black: Sprite = null!;

    _time = 1;
    _d = 0;

    protected onLoad(): void {
        this.black = this.node.getComponentInChildren(Sprite)!;
        this.black.color = color(0, 0, 0, 0);
        this.black.node.active = false;

        input.on(
            Input.EventType.KEY_DOWN,
            (e) => {
                if (e.keyCode !== KeyCode.ARROW_LEFT) {
                    this.show();
                }
                if (e.keyCode !== KeyCode.ARROW_RIGHT) {
                    this.hide();
                }
            },
            this
        );
    }

    _t: Tween<Node> = tween();
    show() {
        this._d = this._time;
        this.black.node.active = true;
    }

    hide() {
        this._d = -this._time;
    }

    protected update(dt: number): void {
        let a = this.black.color.a;
        a += this._d * dt * 255;
        a = Math.min(Math.max(a, 0), 255);
        this.black.node.active = a > 0;
        this.black.color = color(0, 0, 0, a);
    }
}
